package com.yisu.auction.api.web.controller;

import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.yisu.auction.api.core.service.IMemberService;
import com.yisu.auction.api.core.service.ISmsService;
import com.yisu.auction.api.domain.config.SystemConfig;
import com.yisu.auction.api.domain.request.memberPackage.*;
import com.yisu.auction.api.domain.response.memberPackage.MemberInfoResponse;
import com.yisu.auction.api.domain.utils.IpAddrUtil;
import com.yisu.auction.api.domain.vo.memberPackageVos.MemberBaseInfoVo;
import com.yisu.auction.api.web.interceptor.IAuthVerifyAnnotation;
import com.yisu.auction.ewf.common.enums.LoginTypeEnum;
import com.yisu.auction.ewf.common.enums.ResponseCode;
import com.yisu.auction.ewf.common.utils.MD5Util;
import com.yisu.auction.ewf.common.utils.ValidateCodeUtil;
import com.yisu.auction.ewf.common.utils.YunPianMessage;
import com.yisu.auction.ewf.common.web.JsonResult;
import com.yisu.auction.ewf.entity.Member;
import com.yisu.auction.ewf.entity.Sms;
import com.yisu.auction.ewf.entity.UserToken;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.Date;

/**
 * author: 赵杰
 * Business Description：会员业务
 * Date：2017/8/7
 */
@Controller
@RequestMapping(value = "/member")
public class MemberController extends BaseController {
    @Resource
    private IMemberService iMemberService;
    @Resource
    private ISmsService iSmsService;
    @Resource
    private SystemConfig systemConfig;

    /**
     * author: 赵杰
     * Business Description：获取会员基本信息
     *
     * @param memberRequest memberId
     * @return 系统参数
     */
    @RequestMapping(value = "/getMemberBaseInfo", method = {RequestMethod.POST}, produces = "application/json; charset=utf-8")
    @ResponseBody
    @IAuthVerifyAnnotation(Desc = "登录验证", LoginTypeEnum = LoginTypeEnum.NEED_LOGIN)
    public JsonResult getMemberBaseInfo(MemberRequest memberRequest) {
        this.userToken = memberRequest.getUserToken();
        memberRequest.setMemberId(String.valueOf(this.getToken().getMemberId()));
        JsonResult jsonResult = new JsonResult();
        MemberInfoResponse memberInfoResponse = new MemberInfoResponse();
        try {
            MemberBaseInfoVo memberBaseInfoVo = iMemberService.getMemberBaseInfo(memberRequest);
            memberInfoResponse.setMemberBaseInfoVos(memberBaseInfoVo);
        } catch (Exception e) {
            logger.error("获取会员基本信息异常：" + e.getMessage());
        }
        jsonResult.setData(memberInfoResponse);
        return jsonResult;
    }

    /**
     * author: 赵杰
     * Business Description：获取手机验证码
     *
     * @param verificationCodeRequest 登录参数
     * @return
     */
    @RequestMapping(value = "/getVerificationCode", method = {RequestMethod.POST}, produces = "application/json; charset=utf-8")
    @ResponseBody
    @IAuthVerifyAnnotation(Desc = "登录验证", LoginTypeEnum = LoginTypeEnum.NO_NEED_LOGIN)
    public JsonResult getVerificationCode(HttpServletRequest request, VerificationCodeRequest verificationCodeRequest) {
        try {
            if (StringUtils.isEmpty(verificationCodeRequest.getMobile()) || StringUtils.isEmpty(verificationCodeRequest.getType())) {
                return new JsonResult(ResponseCode.FAILURE.code, "参数不完整");
            }
            //找回密码
            if (verificationCodeRequest.getType().equals("1")) {
                MemberRequest memberRequest = new MemberRequest();
                memberRequest.setAppSign(verificationCodeRequest.getAppSign());
                memberRequest.setMobile(verificationCodeRequest.getMobile());
                Member member = iMemberService.getMemberByMobile(memberRequest);
                if (member == null) {
                    return new JsonResult(ResponseCode.FAILURE.code, "该手机未注册");
                }
            } else if (verificationCodeRequest.getType().equals("0") || verificationCodeRequest.getType().equals("2")) {
                if (isRegistered(verificationCodeRequest.getMobile(), verificationCodeRequest.getAppSign())) {
                    return new JsonResult(ResponseCode.FAILURE.code, "该手机号码已注册！");
                }
            }

            String code = ValidateCodeUtil.generate(4); //"1234";//
           /* Sms sms = new Sms();
            sms.setMobile(verificationCodeRequest.getMobile());
            sms.setContent(code);
            sms.setSendTime(new Date());
            sms.setCreateDate(new Date());
            sms.setIsValid(true);
            sms.setStatus(Byte.parseByte("0"));
            sms.setSendType(Byte.parseByte(String.valueOf(Sms.SendTypeEnum.VALIDATE_CODE.code)));
            iSmsService.addValidateCode(sms);
            return new JsonResult();*/
            YunPianMessage message = new YunPianMessage();
            message.setApiKey(systemConfig.getYunPianApiKey());
            message.setText(String.format(systemConfig.getYunPianText(), code));
            message.setMobile(verificationCodeRequest.getMobile());
            String result = ValidateCodeUtil.sendYunPianMessage(systemConfig.getYunPianUrl(), message);
            JsonObject jsonObject = new JsonParser().parse(result).getAsJsonObject();
            int responseCode = jsonObject.get("code").getAsInt();
            if (responseCode == 0) {
                Sms sms = new Sms();
                sms.setMobile(verificationCodeRequest.getMobile());
                sms.setContent(code);
                sms.setSendTime(new Date());
                sms.setCreateDate(new Date());
                sms.setIsValid(true);
                sms.setStatus(Byte.parseByte("0"));
                sms.setSendType(Byte.parseByte(String.valueOf(Sms.SendTypeEnum.VALIDATE_CODE.code)));
                iSmsService.addValidateCode(sms);
                return new JsonResult();
            }
        } catch (Exception e) {
            logger.error("获取手机验证码异常：" + e.getMessage());
        }
        return new JsonResult(ResponseCode.FAILURE.code, "发送失败");
    }

    private boolean isRegistered(String mobile, String appSign) {
        MemberRequest memberRequest = new MemberRequest();
        memberRequest.setAppSign(appSign);
        memberRequest.setMobile(mobile);
        Member member = iMemberService.getMemberByMobile(memberRequest);
        if (member != null) {
            return true;
        }

        return false;
    }


    /**
     * author: LKL
     * Business Description：验证手机验证码
     *
     * @param checkValidateCodeRequest 登录参数
     * @return
     */
    @RequestMapping(value = "/checkValidateCode", method = {RequestMethod.POST}, produces = "application/json; charset=utf-8")
    @ResponseBody
    @IAuthVerifyAnnotation(Desc = "验证验证码", LoginTypeEnum = LoginTypeEnum.NO_NEED_LOGIN)
    public JsonResult checkValidateCode(CheckValidateCodeRequest checkValidateCodeRequest) {
        if (StringUtils.isEmpty(checkValidateCodeRequest.getMobile()) || StringUtils.isEmpty(checkValidateCodeRequest.getCode())
                || StringUtils.isEmpty(checkValidateCodeRequest.getAppSign())) {
            return new JsonResult(ResponseCode.FAILURE.code, "参数不完整");
        }
        //检测用户是否已经注册
        if (checkValidateCodeRequest.getType() != 2 && isRegistered(checkValidateCodeRequest.getMobile(), checkValidateCodeRequest.getAppSign())) {
            return new JsonResult(ResponseCode.FAILURE.code, "该手机号码已经绑定！");
        }
        //检测验证码是否有效
        Sms smsVo = iSmsService.getValidateCodeByMobile(checkValidateCodeRequest.getMobile());
        if (smsVo == null || !checkValidateCodeRequest.getCode().equals(smsVo.getContent())) {
            return new JsonResult(ResponseCode.FAILURE.code, "请输入正确的验证码！");
        }
        return new JsonResult();
    }

    /**
     * author: 赵杰
     * Business Description：手机号码注册
     *
     * @param loginRequest 登录参数
     * @return
     */
    @RequestMapping(value = "/register", method = {RequestMethod.POST}, produces = "application/json; charset=utf-8")
    @ResponseBody
    @IAuthVerifyAnnotation(Desc = "登录验证", LoginTypeEnum = LoginTypeEnum.NO_NEED_LOGIN)
    public JsonResult register(HttpServletRequest request, LoginRequest loginRequest) {
        MemberBaseInfoVo memberBaseInfoVo;
        try {
            if (StringUtils.isEmpty(loginRequest.getMobile()) || StringUtils.isEmpty(loginRequest.getPassword())
                    || StringUtils.isEmpty(loginRequest.getAppSign()) || StringUtils.isEmpty(loginRequest.getCode())) {
                return new JsonResult(ResponseCode.FAILURE.code, "参数不完整");
            }
            String ip = IpAddrUtil.getIpAddr(request); // IP ;
            //检测用户是否已经注册
            if (isRegistered(loginRequest.getMobile(), loginRequest.getAppSign())) {
                return new JsonResult(ResponseCode.FAILURE.code, "该手机号码已注册！");
            }
            //检测验证码是否有效
            Sms smsVo = iSmsService.getValidateCodeByMobile(loginRequest.getMobile());
            if (smsVo == null || !loginRequest.getCode().equals(smsVo.getContent())) {
                return new JsonResult(ResponseCode.FAILURE.code, "请输入正确的验证码！");
            }
            smsVo.setStatus(Byte.parseByte("1"));
            iSmsService.updateValidateCode(smsVo);

            Member insertModel = new Member();
            insertModel.setIp(ip);
            insertModel.setCreateDate(new Date());
            insertModel.setNickname(loginRequest.getNickname());
            insertModel.setWallet(BigDecimal.valueOf(0));
            insertModel.setIco(loginRequest.getIco());
            insertModel.setAddress(IpAddrUtil.getAddress(ip));
            insertModel.setIsValid(true);
            insertModel.setAppType(Integer.valueOf(loginRequest.getAppType()));
            insertModel.setMobile(loginRequest.getMobile());
            insertModel.setAppSign(loginRequest.getAppSign());
            insertModel.setType(Integer.valueOf(3));
            insertModel.setPassword(MD5Util.encode(loginRequest.getPassword()));
            // TODO: 2017/8/11 用户邀请码生成方案未实现
            insertModel.setCode("");
            insertModel.setIntegral(0);
            memberBaseInfoVo = iMemberService.addMember(insertModel);
            if (memberBaseInfoVo != null) {
                return new JsonResult(memberBaseInfoVo);
            }
        } catch (Exception e) {
            logger.error("手机号码注册异常：" + e.getMessage());
        }
        return new JsonResult(ResponseCode.FAILURE.code, "注册失败！");
    }

    /**
     * author: 赵杰
     * Business Description：手机号码登录
     *
     * @param loginRequest 登录参数
     * @return
     */
    @RequestMapping(value = "/login", method = {RequestMethod.POST}, produces = "application/json; charset=utf-8")
    @ResponseBody
    @IAuthVerifyAnnotation(Desc = "登录验证", LoginTypeEnum = LoginTypeEnum.NO_NEED_LOGIN)
    public JsonResult Login(HttpServletRequest request, LoginRequest loginRequest) {
        MemberBaseInfoVo memberBaseInfoVo = new MemberBaseInfoVo();
        JsonResult jsonResult = new JsonResult();
        try {
            if (StringUtils.isEmpty(loginRequest.getMobile()) || StringUtils.isEmpty(loginRequest.getPassword()) || StringUtils.isEmpty(loginRequest.getAppSign())) {
                return new JsonResult(ResponseCode.FAILURE.code, "参数不完整");
            }
            loginRequest.setPassword(MD5Util.encode(loginRequest.getPassword()));
            Member member = iMemberService.getMemberByMobileAndPassword(loginRequest);
            if (member == null) {
                return new JsonResult(ResponseCode.FAILURE.code, "用户帐号或密码不正确！");
            } else {
                UserToken userToken = iMemberService.getUserTokenByMemberId(member.getId());
                memberBaseInfoVo.setAddress(member.getAddress());
                memberBaseInfoVo.setIco(member.getIco());
                memberBaseInfoVo.setId(member.getId());
                memberBaseInfoVo.setToken(userToken.getToken());
                memberBaseInfoVo.setWallet(member.getWallet());
                memberBaseInfoVo.setPresentWallet(member.getPresentWallet());
                memberBaseInfoVo.setNickName(member.getNickname());
                memberBaseInfoVo.setToken(userToken.getToken());
                memberBaseInfoVo.setMobile(member.getMobile());
                return new JsonResult(ResponseCode.SUCCESS.code, ResponseCode.SUCCESS.msg, memberBaseInfoVo);
            }
        } catch (Exception e) {
            logger.error("手机号码登录异常：" + e.getMessage());
        }
        return jsonResult;
    }


    /**
     * author: 赵杰
     * Business Description：第三方登录
     *
     * @param loginRequest 登录参数
     * @return
     */
    @RequestMapping(value = "/thirdLogin", method = {RequestMethod.POST}, produces = "application/json; charset=utf-8")
    @ResponseBody
    @IAuthVerifyAnnotation(Desc = "登录验证", LoginTypeEnum = LoginTypeEnum.NO_NEED_LOGIN)
    public JsonResult thirdLogin(HttpServletRequest request, LoginRequest loginRequest) {
        MemberBaseInfoVo memberBaseInfoVo = new MemberBaseInfoVo();
        String token = "";
        try {
            if (StringUtils.isEmpty(loginRequest.getThirdId()) || StringUtils.isEmpty(loginRequest.getAppSign()) || StringUtils.isEmpty(loginRequest.getType())) {
                return new JsonResult(ResponseCode.PARAMETER_ERROR.code, ResponseCode.PARAMETER_ERROR.msg);
            }
            //检测用户是否存在
            MemberRequest memberRequest = new MemberRequest();
            memberRequest.setAppSign(loginRequest.getAppSign());
            memberRequest.setThirdId(loginRequest.getThirdId());
            Member member = iMemberService.getMemberByThirdIdAndAppSign(memberRequest);
            if (member != null) {
                BigDecimal bg = new BigDecimal("0");
                memberBaseInfoVo.setAddress(member.getAddress());
                memberBaseInfoVo.setIco(member.getIco());
                memberBaseInfoVo.setId(member.getId());
                memberBaseInfoVo.setToken(token);
                memberBaseInfoVo.setWallet(bg);
                memberBaseInfoVo.setPresentWallet(bg);
                memberBaseInfoVo.setNickName(member.getNickname());
                UserToken userToken = iMemberService.getUserTokenByMemberId(member.getId());
                memberBaseInfoVo.setToken(userToken.getToken());
                //当用户存在， 则不再执行任何操作，直接返回结果
                return new JsonResult(ResponseCode.SUCCESS.code, ResponseCode.SUCCESS.msg, memberBaseInfoVo);
            }
            String ip = IpAddrUtil.getIpAddr(request); // IP ;
            Member insertModel = new Member();
            insertModel.setIp(ip);
            insertModel.setCreateDate(new Date());
            insertModel.setNickname(loginRequest.getNickname());
            insertModel.setWallet(BigDecimal.valueOf(0));
            insertModel.setIco(loginRequest.getIco());
            insertModel.setAddress(IpAddrUtil.getAddress(ip));
            insertModel.setIsValid(true);
            insertModel.setAppType(Integer.valueOf(loginRequest.getAppType()));
            insertModel.setThirdId(loginRequest.getThirdId());
            insertModel.setAppSign(loginRequest.getAppSign());
            insertModel.setType(Integer.valueOf(loginRequest.getType()));
            insertModel.setPassword(MD5Util.encode("123456"));
            // TODO: 2017/8/11 用户邀请码生成方案未实现
            insertModel.setCode("");
            insertModel.setIntegral(0);
            memberBaseInfoVo = iMemberService.addMember(insertModel);
            if (memberBaseInfoVo != null) {
                return new JsonResult(memberBaseInfoVo);
            }
        } catch (Exception e) {
            logger.error("第三方登录异常：" + e.getMessage());
        }
        return new JsonResult(ResponseCode.FAILURE.code, ResponseCode.FAILURE.msg, memberBaseInfoVo);
    }


    /**
     * author:黄萧林
     * Business Description:修改用户头像
     *
     * @param memberInfoRequest
     * @return
     */
    @RequestMapping(value = "/updateMemberIco", method = {RequestMethod.POST}, produces = "application/json; charset=utf-8")
    @ResponseBody
    @IAuthVerifyAnnotation(Desc = "登录验证", LoginTypeEnum = LoginTypeEnum.NEED_LOGIN)
    public JsonResult updateMemberIco(MemberInfoRequest memberInfoRequest) {
        if (StringUtils.isEmpty(memberInfoRequest.getIco())) {
            return new JsonResult(ResponseCode.FAILURE.code, "参数不完整");
        }
        this.userToken = memberInfoRequest.getUserToken();
        memberInfoRequest.setMemberId(String.valueOf(this.getToken().getMemberId()));
        if (iMemberService.updateMemberIco(memberInfoRequest)) {
            return new JsonResult(ResponseCode.SUCCESS.code, ResponseCode.SUCCESS.msg);
        }
        return new JsonResult(ResponseCode.FAILURE.code, ResponseCode.FAILURE.msg);
    }

    /**
     * author:黄萧林
     * Business Description:保存用户名
     *
     * @param memberInfoRequest
     * @return
     */
    @RequestMapping(value = "/updateMemberName", method = {RequestMethod.POST}, produces = "application/json; charset=utf-8")
    @ResponseBody
    @IAuthVerifyAnnotation(Desc = "登录验证", LoginTypeEnum = LoginTypeEnum.NEED_LOGIN)
    public JsonResult updateMemberName(MemberInfoRequest memberInfoRequest) {
        if (StringUtils.isEmpty(memberInfoRequest.getMemberName())) {
            return new JsonResult(ResponseCode.FAILURE.code, "参数不完整");
        }
        this.userToken = memberInfoRequest.getUserToken();
        memberInfoRequest.setMemberId(String.valueOf(this.getToken().getMemberId()));
        if (iMemberService.updateMemberName(memberInfoRequest)) {
            return new JsonResult(ResponseCode.SUCCESS.code, ResponseCode.SUCCESS.msg);
        }
        return new JsonResult(ResponseCode.FAILURE.code, ResponseCode.FAILURE.msg);
    }

    /**
     * author:黄萧林
     * Business Description:保存密码
     *
     * @param memberInfoRequest
     * @return
     */
    @RequestMapping(value = "/updateMemberPassword", method = {RequestMethod.POST}, produces = "application/json; charset=utf-8")
    @ResponseBody
    @IAuthVerifyAnnotation(Desc = "登录验证", LoginTypeEnum = LoginTypeEnum.NO_NEED_LOGIN)
    public JsonResult updateMemberPassword(MemberInfoRequest memberInfoRequest) {
        boolean operateStatus = false;
        if (memberInfoRequest.getModifyPasswordType() == null) {
            return new JsonResult(ResponseCode.FAILURE.code, "参数不完整");
        }
        switch (memberInfoRequest.getModifyPasswordType()) {
            case 1:
                if (StringUtils.isEmpty(memberInfoRequest.getOldPassword()) || StringUtils.isEmpty(memberInfoRequest.getPassword()) || StringUtils.isEmpty(memberInfoRequest.getUserToken())) {
                    return new JsonResult(ResponseCode.FAILURE.code, "参数不完整");
                }
                this.userToken = memberInfoRequest.getUserToken();
                memberInfoRequest.setMemberId(String.valueOf(this.getToken().getMemberId()));
                Member updateModel = new Member();
                updateModel.setId(Long.valueOf(memberInfoRequest.getMemberId()));
                updateModel.setPassword(MD5Util.encode(memberInfoRequest.getPassword()));
                operateStatus = iMemberService.updateMemberModel(updateModel);
                break;
            case 2://忘记密码
                if (StringUtils.isEmpty(memberInfoRequest.getPhoneNumber()) || StringUtils.isEmpty(memberInfoRequest.getCode()) || StringUtils.isEmpty(memberInfoRequest.getPassword())) {
                    return new JsonResult(ResponseCode.FAILURE.code, "参数不完整");
                }
                Sms smsVo = iSmsService.getValidateCodeByMobile(memberInfoRequest.getPhoneNumber());
                if (smsVo == null || !memberInfoRequest.getCode().equals(smsVo.getContent())) {
                    return new JsonResult(ResponseCode.FAILURE.code, "请输入正确的验证码！");
                }
                smsVo.setStatus(Byte.parseByte("1"));
                iSmsService.updateValidateCode(smsVo);
                memberInfoRequest.setPassword(MD5Util.encode(memberInfoRequest.getPassword()));
                operateStatus = iMemberService.updateMemberPasswordForNoLogin(memberInfoRequest);
                break;
        }
        if (operateStatus) {
            return new JsonResult(ResponseCode.SUCCESS.code, ResponseCode.SUCCESS.msg);
        }
        return new JsonResult(ResponseCode.FAILURE.code, ResponseCode.FAILURE.msg);
    }

    /**
     * author:黄萧林
     * Business Description:保存手机号
     *
     * @param memberInfoRequest
     * @return
     */
    @RequestMapping(value = "/updateMemberPhoneNumber", method = {RequestMethod.POST}, produces = "application/json; charset=utf-8")
    @ResponseBody
    @IAuthVerifyAnnotation(Desc = "登录验证", LoginTypeEnum = LoginTypeEnum.NEED_LOGIN)
    public JsonResult updateMemberPhoneNumber(MemberInfoRequest memberInfoRequest) {
        if (StringUtils.isEmpty(memberInfoRequest.getCode()) || StringUtils.isEmpty(memberInfoRequest.getPhoneNumber())
                || StringUtils.isEmpty(memberInfoRequest.getAppSign())) {
            return new JsonResult(ResponseCode.FAILURE.code, "参数不完整");
        }

        if (isRegistered(memberInfoRequest.getPhoneNumber(), memberInfoRequest.getAppSign())) {
            return new JsonResult(ResponseCode.FAILURE.code, "该手机号码已经绑定！");
        }

        Sms smsVo = iSmsService.getValidateCodeByMobile(memberInfoRequest.getPhoneNumber());
        if (smsVo == null || !memberInfoRequest.getCode().equals(smsVo.getContent())) {
            return new JsonResult(ResponseCode.FAILURE.code, "请输入正确的验证码！");
        }
        smsVo.setStatus(Byte.parseByte("1"));
        iSmsService.updateValidateCode(smsVo);
        this.userToken = memberInfoRequest.getUserToken();
        memberInfoRequest.setMemberId(String.valueOf(this.getToken().getMemberId()));
        if (iMemberService.updateMemberPhoneNumber(memberInfoRequest)) {
            return new JsonResult(ResponseCode.SUCCESS.code, ResponseCode.SUCCESS.msg);
        }
        return new JsonResult(ResponseCode.FAILURE.code, ResponseCode.FAILURE.msg);
    }
}
